package com.jic.market.impl;

import java.lang.Long;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.member.exception.AppRuntimeException;
import com.jic.enums.RedisKey;
import com.jic.market.entity.BargainLog;
import com.jic.market.entity.MyBargain;
import com.jic.market.entity.ProductBargain;
import com.jic.market.entity.PromotionBargain;
import com.jic.market.mapper.PromotionMyBargainMapper;
import com.jic.market.request.rest.bargain.MyBargainQueryRestRequest;
import com.jic.market.request.rest.bargain.MyBargainSaveRestRequest;
import com.jic.market.response.rest.bargain.MyBargainRestResponse;
import com.jic.market.service.BargainLogService;
import com.jic.market.service.MyBargainService;
import com.jic.market.service.ProductBargainService;
import com.jic.market.service.PromotionBargainService;
import com.jic.member.api.rest.MememberApi;
import com.jic.member.request.MememberUserRequest;
import com.jic.member.response.MememberUserResponse;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 我的砍价商品表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-09-10 06:20:01
 */
@Service
@Slf4j
public class MyBargainServiceImpl implements MyBargainService {

    @Autowired
    private PromotionMyBargainMapper myBargainMapper;

    @Autowired
    private ProductListApi productListApi;

    @Autowired
    private ProductBargainService productBargainService;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Autowired
    private BargainLogService bargainLogService;

    @Autowired
    private MememberApi mememberApi;

    @Autowired
    PromotionBargainService promotionBargainService;


    @Override
    public long insert(MyBargain myBargain) {
        long flag = myBargainMapper.insert(myBargain);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return myBargainMapper.delete(id);
    }

    @Override
    public long update(MyBargain myBargain) {
        return myBargainMapper.update(myBargain);
    }

    @Override
    public MyBargain queryByPrimaryKey(Long id) {
        return myBargainMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<MyBargain> query(MyBargain myBargain) {
        return myBargainMapper.query(myBargain);
    }

    @Override
    public PageResult<MyBargain> queryPage(MyBargain myBargain, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MyBargain> list = myBargainMapper.queryPage(startIndex, pageQuery.getLimit(), myBargain);
        long count = myBargainMapper.queryPageCount(myBargain);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public PageResult<MyBargainRestResponse> listRestPage(MyBargainQueryRestRequest myBargainRestRequest, Page pageQuery) {
        //计算下标
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + myBargainRestRequest.getToken());
        MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
        if (mMember == null) {
            throw new AppRuntimeException("9999", "用户未登录");
        }
        myBargainRestRequest.setMemeberId(mMember.getId());
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MyBargainRestResponse> list = myBargainMapper.listRestPage(startIndex, pageQuery.getLimit(), myBargainRestRequest);
        long count = myBargainMapper.listRestPageCount(myBargainRestRequest);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item -> {
                //商品信息
                RestResult<ProductAfterInfoByIdResponse> responseRestResult =
                        productListApi.queryProductInfoById(item.getProductId());
                if (responseRestResult != null && responseRestResult.getData() != null) {
                    item.setChineseName(responseRestResult.getData().getChineseName());
                    item.setUrl(responseRestResult.getData().getPictureUrl());
                    item.setPrice(responseRestResult.getData().getSalePriceWithTax());
                    //当前价格
                    BargainLog bargainLog = new BargainLog();
                    bargainLog.setFightMasterId(item.getId());
                    bargainLog.setDeleteFlag(0);
                    BigDecimal bigDecimal = bargainLogService.bargainMoneyCount(bargainLog);
                    if (bigDecimal == null) {
                        item.setNowPrice(responseRestResult.getData().getSalePriceWithTax());
                    } else {
                        item.setNowPrice(responseRestResult.getData().getSalePriceWithTax().subtract(bigDecimal));
                    }
                }

                //最低价
                ProductBargain productBargain = new ProductBargain();
                productBargain.setDeleteFlag(0L);
                productBargain.setBargainId(item.getBargainId());
                productBargain.setProductId(item.getProductId());
                List<ProductBargain> productBargainList = productBargainService.query(productBargain);
                if (CollectionUtils.isNotEmpty(productBargainList)) {
                    item.setFloorPrice(productBargainList.get(0).getFloorPrice());
                }

                //当前剩余时间
                PromotionBargain promotionBargain = promotionBargainService.queryByPrimaryKey(item.getBargainId());
                if (productBargain != null) {
                    long time = getTime(promotionBargain.getTime(), item.getCreateTime());
                    if (time > 0) {
                        item.setTime(time);
                        item.setStatus(1);
                    } else {
                        item.setStatus(2);
                    }

                }
            });
        }
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MyBargainRestResponse helpBargain(MyBargainSaveRestRequest myBargainSaveRestRequest) {
        try {
            String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + myBargainSaveRestRequest.getToken());
            MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
            log.info("开始进入立即砍价/继续砍价===========》》" + myBargainSaveRestRequest.toString());
            //返回实体
            MyBargainRestResponse myBargainRestResponse = new MyBargainRestResponse();

            //获取活动限制刀数
            ProductBargain productBargain = new ProductBargain();
            productBargain.setBargainId(myBargainSaveRestRequest.getBargainId());
            productBargain.setProductId(myBargainSaveRestRequest.getProductId());
            productBargain.setDeleteFlag(0L);
            List<ProductBargain> productBargainList = productBargainService.query(productBargain);

            //获取商品原价
            RestResult<ProductAfterInfoByIdResponse> responseRestResult = productListApi.queryProductInfoById(myBargainSaveRestRequest.getProductId());

            //type 1立即砍价 2 继续砍价
            if (myBargainSaveRestRequest.getType() == 1) {
                //插入我的砍价
                MyBargain myBargain = new MyBargain();
                myBargain.setBargainId(myBargainSaveRestRequest.getBargainId());
                myBargain.setProductId(myBargainSaveRestRequest.getProductId());
                myBargain.setMemberId(mMember.getId());
                myBargain.setCreateTime(new Date());
                myBargain.setUpdateTime(new Date());
                myBargain.setDeleteFlag(0);
                myBargainMapper.insert(myBargain);

                //插入我的砍价记录
                BargainLog bargainLog = new BargainLog();
                bargainLog.setFightMasterId(myBargain.getId());
                bargainLog.setMemberId(mMember.getId());
                bargainLog.setCreateTime(new Date());
                bargainLog.setUpdateTime(new Date());
                bargainLog.setDeleteFlag(0);
                BigDecimal cutPrice = BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(productBargainList) && responseRestResult != null && responseRestResult.getData() != null) {
                    cutPrice = getCutPrice(productBargainList.get(0).getNumber(), responseRestResult.getData().getSalePriceWithTax(), new BigDecimal(0), 0);
                    bargainLog.setBargainMoney(cutPrice);
                }

                bargainLogService.insert(bargainLog);
                myBargainRestResponse.setNowCutPrice(cutPrice);

                //更新我的砍价价格
                MyBargain myBargain1 = new MyBargain();
                if (responseRestResult != null && responseRestResult.getData() != null) {
                    BigDecimal price = responseRestResult.getData().getSalePriceWithTax().subtract(cutPrice);
                    if (price.compareTo(BigDecimal.ZERO) == 0) {
                        price = responseRestResult.getData().getSalePriceWithTax();
                    }
                    myBargain1.setBuyPrice(price);
                }
                myBargain1.setId(myBargain.getId());
                myBargainMapper.update(myBargain1);

            } else {
                //插入我的砍价
                BargainLog bargainLog = new BargainLog();
                bargainLog.setFightMasterId(myBargainSaveRestRequest.getId());
                BigDecimal bigDecimal = bargainLogService.bargainMoneyCount(bargainLog);
                bargainLog.setMemberId(mMember.getId());
                bargainLog.setCreateTime(new Date());
                bargainLog.setUpdateTime(new Date());
                List<BargainLog> bargainList = bargainLogService.query(new BargainLog() {{
                    setFightMasterId(myBargainSaveRestRequest.getId());
                    setMemberId(mMember.getId());
                    setDeleteFlag(0);
                }});
                if (CollectionUtils.isEmpty(bargainList)){
                    List<BargainLog> bargainLogList = bargainLogService.query(new BargainLog() {{
                        setFightMasterId(myBargainSaveRestRequest.getId());
                        setDeleteFlag(0);
                    }});
                    BigDecimal cutPrice = BigDecimal.ZERO;
                    boolean b = CollectionUtils.isNotEmpty(productBargainList) && responseRestResult != null && responseRestResult.getData() != null
                            && bigDecimal != null && CollectionUtils.isNotEmpty(bargainLogList);
                    if (b) {
                        cutPrice = getCutPrice(productBargainList.get(0).getNumber(), responseRestResult.getData().getSalePriceWithTax(), bigDecimal, bargainLogList.size());
                        bargainLog.setBargainMoney(cutPrice);
                    }
                    bargainLog.setDeleteFlag(0);
                    bargainLogService.insert(bargainLog);

                    //返回砍价信息
                    myBargainRestResponse.setNowCutPrice(cutPrice);
                    MyBargain myBargain = myBargainMapper.queryByPrimaryKey(myBargainSaveRestRequest.getId());

                    if (myBargain != null) {

                        //更新我的砍价价格
                        MyBargain myBargain1 = new MyBargain();
                        if (responseRestResult != null && responseRestResult.getData() != null && myBargain.getBuyPrice() != null) {
                            myBargain1.setBuyPrice(myBargain.getBuyPrice().subtract(cutPrice));
                        }
                        myBargain1.setId(myBargainSaveRestRequest.getId());
                        myBargainMapper.update(myBargain1);

                        RestResult<MememberUserResponse> mememberUserResponseRestResult = mememberApi.queryMemberUserInfo(myBargain.getMemberId());
                        if (mememberUserResponseRestResult != null && mememberUserResponseRestResult.getData() != null) {
                            myBargainRestResponse.setMemberName(mememberUserResponseRestResult.getData().getNickName());
                        }
                    }
                }

            }
            return myBargainRestResponse;
        } catch (Exception e) {
            log.error("开始进入立即砍价/继续砍价失败=========》", e);
            throw new AppRuntimeException("9999", e);
        }
    }


    //获取活动结束时间戳
    public long getTime(Integer hours, Date createTime) {
        if (hours == null || createTime == null) {
            return -1;
        }
        long l1 = createTime.getTime();
        long l2 = hours * 60 * 60 * 1000;
        long l3 = new Date().getTime();
        return l1 + l2 - l3;
    }


    /*获取本次砍价价格
     * count 总刀数
     * price 原价
     * alreadyPrice 已砍价格
     * cutNum  当前刀数
     * */
    private BigDecimal getCutPrice(long count, BigDecimal price, BigDecimal alreadyPrice, long cutNum) {
        //此次砍价的最低钱数（总价-已砍总价/总次数-已砍次数）（相当于是向上随机）（转换为单位分）
        Integer min = (price.subtract(alreadyPrice)).divide(new BigDecimal(count - cutNum), 2, BigDecimal.ROUND_UP).multiply(new BigDecimal(100)).intValue();
        //此次砍价的最高钱数（最低价格的2倍）
        //这个倍数越高，砍价的幅度跳动越大。建议设置到1-2.（不能超过2.因为有可到导致总刀数不准确）
        Integer max = min * 2;
        //此次砍的价格（最低钱数到最高钱数的随机）
        BigDecimal cutPrice = new BigDecimal(min + new Random().nextInt(max - min)).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_UP);
        //最后一刀保证价格准确
        if (cutNum == count - 1) {
            cutPrice = price.subtract(alreadyPrice);
        }
        return cutPrice;
    }

}